<template>
  <view class="read">
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">{{post.article_title}}</block>
    </cu-custom>
    <view class="cu-load load-modal" v-if="loadModal">
      <!-- <view class="cuIcon-emojifill text-orange"></view> -->
      <image :src="imgUrl+'static/loading.gif'" mode="aspectFit"></image>
      <view class="gray-text">{{hint}}</view>
    </view>
    <view class="load-progress" :class="loadProgress!=0?'show':'hide'" :style="[{top:CustomBar+'px'}]">
      <view class="load-progress-bar bg-green" :style="[{transform: 'translate3d(-' + (100-loadProgress) + '%, 0px, 0px)'}]"></view>
      <view class="load-progress-spinner text-green"></view>
    </view>
    <view class="cu-card dynamic">
      <view class="cu-list menu menu-avatar">
        <view class="cu-item">
          <view class="cu-avatar round lg" v-if="post.adminData"  :style="'background-image:url('+post.adminData[0].admin_cover+');'"></view>
          <view class='content flex-sub'>
            <view class='text-blod cite'>{{post.article_title}}</view>
            <view class='text-gray text-sm flex justify-between'>
              <text class="cuIcon-people">{{post.adminData[0].admin_name}}</text>
              <text class="cuIcon-time">{{post.article_time}}</text>
              <text class="cuIcon-attention">{{!!post.pageView?post.pageView:0}}</text>
              <text :class="Operate.islike?'cuIcon-appreciatefill text-red':'cuIcon-appreciate text-gray'">{{post.likeNum}}</text>
              <text class="cuIcon-message"> {{!!post.discussNum?post.discussNum:0}}</text>
            </view>
          </view>
        </view>
        <view class='text-content' id='b_comment'>
          <view class='contarin'>
            <jyf-parser :html="post.article_content"></jyf-parser>
          </view>
        </view>
				
				<view class="like-area flex-sub text-center padding" v-if="isShowDonate">
					<view class="cu-avatar xl round" :class="'bg-'+color" @click="openDonate()">
						赏
					</view>
					<view class="padding">您的支持是对我最大的鼓励</view>
				</view>
				
				<view class="cu-bar bg-white solid-bottom">
				  <view class='action'>
				    <text class='icon-titles text-orange '></text>
				    <view class="cu-capsule radius">
				      <view class='cu-tag bg-green'>点赞</view>
				      <view class='cu-tag line-green'>{{post.likeNum}}</view>
				    </view>
				  </view>
				</view>
				<view class="bg-white">
				<scroll-view scroll-x="true" scroll-with-animation>
					<view class="cu-avatar-group ">
						<view class="cu-avatar bg-white round lg" v-for="(item,index) in avatarList" :key="index" :style="[{ backgroundImage:'url(' + item.user_cover + ')' }]"></view>
					</view>
				</scroll-view>
				</view>
        <view class="cu-bar bg-white solid-bottom">
          <view class='action'>
            <text class='icon-titles text-orange '></text>
            <view class="cu-capsule radius">
              <view class='cu-tag bg-red'>评论</view>
              <view class='cu-tag line-red'>{{total}}</view>
            </view>
          </view>
        </view>

        <view class="cu-list menu menu-avatar comment solids-top">
          <block v-if="comments.length>0">
          <view class="cu-item" v-for="(item,index) in comments" @click.stop='onReply' data-url="../home/reply"
            :data-item='item' :key="index">

            <view class="cu-avatar round" :style="'background-image:url('+item.userData[0].user_cover+');'"></view>
            <view class='content'>
              <view class="text-blod">{{item.userData[0].user_name}}</view>
              <view class='text-black text-df'>
                {{item.comment_body}}
              </view>
              <block v-if="isReply" v-for="(reply,idx) in item.son" :for-item='reply' :key="idx">
                <view  class='bg-gray padding-sm radius margin-top-sm  text-sm' v-if="reply.reply_yes">
                  <view class="flex">
                    <view class="text-blod text-blue">{{reply.user_name}}</view> :
                    <view class='flex-sub text-grey'>{{reply.reply_body}}</view>
                  </view>
                </view>
              </block>
              <view class='margin-top-sm flex justify-between'>
                <view class='text-gray text-df'>{{item.comment_time}}</view>
                <view>
                  <text class="cuIcon-appreciatefill" :class="item.liked?'text-red':'text-gray'" @click.stop='zan'
                    :data-id='item._id' :data-index='index'>
                    <text v-if='item.total>0'>{{item.total}}</text>
                  </text>
                  <text v-if="isReply" class="cuIcon-messagefill text-gray margin-left-sm"></text>
                </view>
              </view>
            </view>
          </view>
        </block>
        <view class="noData" v-else>
          <image :src="imgUrl+'static/noNews.jpg'" class="noImg" mode="aspectFit"></image>
          <text class="noTitle">{{nodata_str}}</text>
        </view>
        </view>
      </view>
    </view>
		<view v-if="comments.length>0" class='cu-load bg-mauve over'></view>
      <view class="cu-bar foot input" :style="'bottom:'+InputBottom+'px'">
        <input class="solid-bottom" v-model="input" maxlength="80" cursor-spacing="10" ></input>
        <button class='cu-btn round bg-red shadow' @click='onComment'>发表</button>
        <view class="action" @tap='onCollection' name='collection'>
          <text :class="Operate.iscolle?'cuIcon-favorfill text-yellow':'cuIcon-favor text-gery'"></text>
        </view>
        <view class="action" @tap='onLike' name='like'>
          <text :class="Operate.islike?'cuIcon-likefill text-red':'cuIcon-like text-gery'"></text>
        </view>
				<view class="action" @tap='onPoster' name='poster'>
				  <text class="cuIcon-forwardfill text-green"></text>
				</view>
      </view>
			
			<view class="cu-modal" :class="modalName=='DialogModal1'?'show':''">
				<view class="cu-dialog">
					<view class="cu-bar bg-white justify-end">
						<view class="content">授权登录</view>
						<view class="action" @tap="hideModal">
							<text class="cuIcon-close text-red"></text>
						</view>
					</view>
					<view class="padding-xl">
						1、评论，点赞需要授权登录<br />
						2、授权会获取您的头像和昵称
					</view>
					<view class="cu-bar bg-white justify-end">
						<view class="action">
							<button class="cu-btn line-green text-green" @tap="hideModal">取消</button>
							<button class="cu-btn bg-green margin-left" open-type="getUserInfo" @getuserinfo="comfirmModal">确定</button>
						</view>
					</view>
				</view>
			</view>
			
			<view class="cu-modal" v-if="loadDialogModal2" :class="modalName=='DialogModal2'?'show':''">
				<view class="cu-dialog">
					<view class="cu-bar bg-white justify-end">
						<view class="content">保存海报</view>
						<view class="action" @tap="hidePoster">
							<text class="cuIcon-close text-red"></text>
						</view>
					</view>
					<wm-poster Width="680" :imgSrc="poster.imgUrl" :QrSrc="poster.qrUrl" :Title="poster.title" :Referrer="poster.referrer" @success="posterGetSuccess"></wm-poster>
					<view class="cu-bar bg-white justify-end">
						<view class="action">
							<button class="cu-btn line-green text-green" @tap="hidePoster">取消</button>
							<button class="cu-btn bg-green margin-left" @tap="savePoster">保存</button>
						</view>
					</view>
				</view>
			</view>
  </view>
</template>

<script>
	const db = wx.cloud.database();
  import util from '../../utils/util.js';
  import time from '../../utils/time.js';
  import parser from "@/components/jyf-parser/jyf-parser"; // HbuilderX 2.5.5 及以上可以不需要
  import Prism from "@/components/jyf-parser/libs/prism.js"; //语法高亮
	import wmPoster from "@/libs/wm-poster/wm-poster.vue";
	import marked from '@/libs/marked/marked.min.js'

  export default {
    data() {
      return {
        imgUrl:getApp().globalData.imgUrl,
        CustomBar: getApp().globalData.CustomBar,
				isExamine:getApp().globalData.isExamine,
				isReply: getApp().globalData.isReply,
				isShowDonate: getApp().globalData.isShowDonate,
				donateQrURL:getApp().globalData.imgUrl+getApp().globalData.admire,
				color: getApp().globalData.color,
				InputBottom:0,
        loadModal: false, //加载
        loadProgress: 0, //加载进度
        hint: '加载中...', //加载提示
        total: 0, //评论量
        pageInex: 1, //评论第一页
        pageSize: 6, //每页条数
				userInfo:null,
        input: '',
        id: 0,//文章id
        liked: true,
        iscollec: false,
        post: {},
        comments: [],
        Operate: {
          isbrowse: false, //是否浏览过
          iscolle: false, //是否收藏过
          iscomme: false, //是否评论
          isliek: false, //是否点赞
        },
				modalName: null,
				avatarList:[],//点赞人
				nodata_str: '暂无评论，赶紧抢沙发吧',
				loadDialogModal2: false,//是否展示海报弹窗
				posterURL: '',//海报下载地址
				poster:{
					title:'',
					referrer:'',
					imgUrl: '',//海报地址
					qrUrl:'',
				}
      }
    },
    components: {
      "jyf-parser": parser,
			"wm-poster":wmPoster
    },
    onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			this.id = option.id;
      let userInfo =getApp().globalData.userInfo;
      if (Object.keys(userInfo).length>0) {
        this.userInfo = userInfo;		
				this.myOperate();
      }
      this.getBlog();   
			this.getLikeAll();  
      this.browse();
    },
    onShow: function(){
			this.updateUserInfo('read');
			this.pageInex = 1;
      this.getComment('up');
    },
    methods: {
			showModal() {
				this.modalName = "DialogModal1"
			},
			comfirmModal(e) {
				let that = this;
				this.modalName = null;
				if (e.detail.userInfo){
				  this.getUser();
					
				  }else{
				    uni.showToast({
				      title: '取消授权成功！',
				      icon: 'none',
				      duration: 2000
				    })
				  } 	
			},
			hideModal() {
				this.modalName = null
			},
			openDonate() {
				uni.previewImage({
					urls: [this.donateQrURL],
				});
			},
			getUser: function(){
			  let _this = this;
			  uni.vibrateShort({})
			  // 调用云函数
			  wx.cloud.callFunction({
			    name: 'login',
			    data: {},
			    success: res => {
			       // console.log(res)
			      //查看用户是否注册过了
			      db.collection('user').where({
			        user_id: res.result.openid, // 填入当前用户 openid
			      }).get().then(re => {
			        if (re.data.length > 0) {
			          //已经保存过用户信息
			          console.log("该微信用户已授权！！！")
								uni.getUserInfo({
									success: function(r) {
										//保存
										db.collection('user').where({
											user_id: res.result.openid 
										}).update({
												data: {
													user_name: r.userInfo.nickName,
													user_cover: r.userInfo.avatarUrl,
													user_gender: r.userInfo.gender,
													user_province: r.userInfo.province,
													user_city: r.userInfo.city,
													user_country: r.userInfo.country
												}
											})
									}
								})
			        } else {
			          //未保存获取用户信息
			          uni.getUserInfo({
			            success: function(r) {
			              //保存
			              let join_date = new Date().getTime();
			              db.collection('user').add({
			                  // data 字段表示需新增的 JSON 数据
			                  data: {
			                    user_id: res.result.openid,
			                    user_name: r.userInfo.nickName,
			                    user_cover: r.userInfo.avatarUrl,
			                    user_gender: r.userInfo.gender,
			                    user_province: r.userInfo.province,
			                    user_city: r.userInfo.city,
			                    user_country: r.userInfo.country,
			                    join_date: join_date,
			                  }
			                }).then(res => {
			                  console.log("用户授权成功！！！")
			                  console.log(res)
			                })
			                .catch(console.error)
			            }
			          })
			        }
			  
			        db.collection('user').where({
			          user_id: res.result.openid // 填入当前用户 openid
			        }).get().then(rs => {
			          getApp().globalData.userInfo = rs.data[0];
			          getApp().globalData.hasUserInfo = true;
			          _this.userInfo=rs.data[0];
								this.myOperate();
			        })
			        wx.hideLoading();
			      })
			    },
			    fail: err => {
			      console.error('[云函数] [login] 调用失败', err)
			    }
			  })
			},
      getBlog() { //文章内容
        if (this.loadProgress < 100) {
          setTimeout(() => {
            this.loadProgress = this.loadProgress + 3;
          }, 300)
        }
        wx.cloud.callFunction({
          name: 'getRead',
          data: {
            id: this.id
          },
          success: res => {
            this.loadProgress = 0; //加载完成
            let data = res.result.list[0];
						data.article_content = marked(data.article_content);
            data.article_time = util(parseInt(data.article_time));
            this.post = data;
            // console.log(res)
          },
          fail: err => {
            console.error('[云函数] [getRead] 调用失败', err)
          }
        })
      },
			getLikeAll(){
				wx.cloud.callFunction({
				  name: 'getLikeAll',
				  data: {
				    id: this.id
				  },
				  success: res => {
						this.avatarList = res.result.list;
				  },
				  fail: err => {
				    console.error('[云函数] [getLikeAll] 调用失败', err)
				  }
				})
			},
      getComment(refresh = '') { //评论列表
        this.hint = refresh == 'below' ? '刷新中...' : '加载中...';
        if (refresh == 'below'||this.pageInex==1) {
          this.comments = {};
        } //清空评论列表
        this.loadModal = true;
        wx.cloud.callFunction({
          name: 'getComment',
          data: {
            id: this.id,
						status: 1,
            pageInex: this.pageInex,
            pageSize: this.pageSize
          },
          success: res => {
            this.loadModal = false;
            uni.stopPullDownRefresh();
            let list = res.result.list;
            this.total = res.result.total;
            list.map(item => {
              item.comment_time = time(item.comment_time);
              let liked = 0; //是否点赞过
              item.total = 0; //统计评论点赞量
              item.replyNum = 0; //回复量
              item.son.map(it => {
                it.reply_time = time(it.reply_time);
                if (!it.reply_yes) {
                  item.total = item.total + 1;
                  if (this.userInfo&&it.user_id == this.userInfo.user_id) {
                    liked = liked + 1;
                  }
                } else {
                  item.replyNum = item.replyNum + 1;
                }
              })
              item.liked = liked > 0 ? true : false;
            })
            this.comments = this.pageInex == 1 ? list : [...this.comments, ...list];
            if (list.length == 0) {
              uni.showToast({
                title: '没有更多评论了！',
                icon: 'none',
                duration: 2000
              })
            }
            // console.log(this.comments);
          },
          fail: err => {
            console.error('[云函数] [getComment] 调用失败', err)
          }
        })
      },
      myOperate() { //我的状态
        wx.cloud.callFunction({
          name: 'myOperate',
          data: {
            article_id: this.id,
            user_id: this.userInfo.user_id
          },
          success: res => {
            this.Operate = res.result;
            // console.log(res)
          },
          fail: err => {
            console.error('[云函数] [myOperate] 调用失败', err)
          }
        })
      },
      onReply(e) { //跳转回复
				if(!this.isReply){
					return;
				}
				if(!this.userInfo){
					this.showModal();
					return;
				}
        let {
          url,
          item
        } = e.currentTarget.dataset;
        uni.navigateTo({
          url: `${url}?direct=${JSON.stringify(item)}`
        })
      },

      onComment() { //评论
        uni.vibrateShort({})
        if (this.input) {
          if (this.userInfo) {
            wx.cloud.callFunction({
              name: 'addComment',
              data: {
                id: this.post._id,
                user_id: this.userInfo.user_id,
                comment: this.input,
								status: this.isExamine?0:1,
              },
              success: res => {
                if (res.result.errMsg == 'collection.add:ok') {
                  this.input = '';
									if (this.isExamine) {
										uni.showToast({
											title: "请等待审核",
											duration: 2000
										});
									} else{
										this.pageInex = 1;
										this.getComment();
										this.post.discussNum = this.post.discussNum + 1;
										uni.showToast({
										  title: '评论成功',
										  duration: 1500
										})
										setTimeout(() => {
										  this.tobottom()
										}, 1500)
									}
                }
              },
              fail: err => {
                console.error('[云函数] [addComment] 调用失败', err)
              }
            })
          } else {
						this.showModal();
						return;
            // uni.navigateTo({
            //   url: '../login/login',
            // })
          }
        } else {
          wx.showToast({
            title: '输入不能为空',
            icon: 'none'
          })
        }
      },
      tobottom() {
        uni.createSelectorQuery().select('#b_comment').boundingClientRect(function(rect) {
          // 使页面滚动到底部
          uni.pageScrollTo({
            scrollTop: rect.bottom
          })
        }).exec()
      },
      zan(e) { //点赞评论
        uni.vibrateShort({})
        if (this.userInfo) {
          let {
            id,
            index
          } = e.currentTarget.dataset;
          wx.cloud.callFunction({
            name: 'addZan',
            data: {
              id: id,
              user_id: this.userInfo.user_id
            },
            success: res => {
              this.comments[index].liked = !this.comments[index].liked;
              this.comments[index].total = this.comments[index].liked ? this.comments[index].total + 1 : this.comments[
                index].total - 1;
              let title = this.comments[index].liked ? '点赞成功' : '取消点赞成功';
              uni.showToast({
                title,
                duration: 1500
              })
              // console.log(res)
            },
            fail: err => {
              console.error('[云函数] [addZan] 调用失败', err)
            }
          })
        } else {
					this.showModal();
					return;
          // uni.navigateTo({
          //   url: '../login/login',
          // })
        }
      },
      onCollection() { //收藏
        uni.vibrateShort({})
        if (this.userInfo) {
          wx.cloud.callFunction({
            name: 'addCollection',
            data: {
              id: this.post._id,
              user_id: this.userInfo.user_id
            },
            success: res => {
              this.post.collectNum =!this.Operate.iscolle? this.post.collectNum + 1:this.post.collectNum - 1;
              let title=!this.Operate.iscolle? '收藏成功':'取消收藏成功';
              this.Operate.iscolle=!this.Operate.iscolle;
              uni.showToast({
                title,
                duration: 1500
              })

              // console.log(res)
            },
            fail: err => {
              console.error('[云函数] [addCollection] 调用失败', err)
            }
          })
        } else {
					this.showModal();
					return;
          // uni.navigateTo({
          //   url: '../login/login',
          // })
        }
      },
      onLike() {
				let _this=this;
        uni.vibrateShort({})
        if (this.userInfo) {
          wx.cloud.callFunction({
            name: 'addLike',
            data: {
              id: this.post._id,
              user_id: this.userInfo.user_id
            },
            success: res => {
              this.post.likeNum =!this.Operate.islike? this.post.likeNum + 1:this.post.likeNum - 1;
							if(!this.Operate.islike){
								_this.avatarList.unshift({ user_cover: _this.userInfo.user_cover,user_name: _this.userInfo.user_name,user_id: _this.userInfo.user_id})
							}else{
								var nowUser = _this.avatarList.filter((p) => {
								    return p.user_id == _this.userInfo.user_id;
								});
								var index = _this.avatarList.indexOf(nowUser[0]);
								index > -1 && _this.avatarList.splice(index, 1);
							}
              let title=!this.Operate.islike? '点赞成功':'取消点赞成功';
              this.Operate.islike=!this.Operate.islike;
              uni.showToast({
                title,
                duration: 1500
              })     
                // console.log(res)
            },
            fail: err => {
              console.error('[云函数] [addLike] 调用失败', err)
            }
          })
        } else {
					this.showModal();
					return;
          // uni.navigateTo({
          //   url: '../login/login',
          // })
        }
      },
      onPoster(){//生成海报
				uni.showLoading({
					title: "生成海报中",
					mask: false
				});
			  this.loadDialogModal2= true;
				this.poster={
					title:this.post.article_title,
					referrer:this.userInfo?`${this.userInfo.user_name}分享给你`:'分享给你',
					imgUrl: this.post.article_cover,//海报地址
					qrUrl:this.imgUrl+getApp().globalData.QRcode
				}
			},
			posterGetSuccess(res) {
				uni.hideLoading();
				this.modalName = 'DialogModal2';
				this.posterURL = res.tempFilePath;
			},
			savePoster() {
				let that = this;
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success() {
						uni.saveImageToPhotosAlbum({
							filePath: that.posterURL,
							success: function() {
								that.loadDialogModal2 = false;
								that.modalName = "";
							}
						});
					}
				})
			},
			hidePoster() {
				this.loadDialogModal2 = false;
				this.modalName = '';
			},
			browse (){//浏览
        if (this.userInfo) {
          wx.cloud.callFunction({
            name: 'addBrowse',
            data: {
              id: this.id,
              user_id: this.userInfo.user_id
            },
            success: res => {
              this.post.pageView =this.post.pageView + res.result.inc;
              this.Operate.isbrowse=true;
            },
            fail: err => {
              console.error('[云函数] [addBrowse] 调用失败', err)
            }
          })
          }
      }
    },

    onPullDownRefresh() { //下拉刷新
      this.pageInex = 1;
      this.getComment('below');
      // console.log('onPullDownRefresh');
    },
    onReachBottom() { //上拉加载
      this.pageInex = this.pageInex + 1;
      this.getComment('up');
      // console.log('onReachBottom');
    },
		onShareAppMessage: function(res) {//调用API分享给好友
			return {
				title: this.post.article_title,
				imageUrl: this.post.article_cover,   //图片地址
				path: `/pages/home/read?id=${this.id}`,
				success: function success(res) {
					console.log("转发成功", res);
				},
				fail: function fail(res) {
					console.log("转发失败", res);
				}
			}
		},
		onShareTimeline: function(res) {//调用API分享朋友圈
			return {
				title: this.post.article_title,
				imageUrl: this.post.article_cover,   //图片地址
				path: `/pages/home/read?id=${this.id}`,
				success: function success(res) {
					console.log("转发成功", res);
				},
				fail: function fail(res) {
					console.log("转发失败", res);
				}
			}
		},
  }
</script>

<style>
  @import '../../components/jyf-parser/libs/prism.css';

  .img-plus-style {
    background: cornflowerblue;
    height: 100rpx;
    width: 100rpx;
    position: absolute;
    bottom: 150rpx;
    right: 60rpx;
    z-index: 1;
    border-radius: 50%;
    line-height: 100rpx;
    font-size: 20rpx;

  }

  .img-style {
    background: darkcyan;
    height: 100rpx;
    width: 100rpx;
    position: absolute;
    bottom: 150rpx;
    right: 60rpx;
    opacity: 0;
    border-radius: 50%;
    line-height: 100rpx;
    font-size: 20rpx;
  }

  .poster-btn {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    box-shadow: 2rpx 2rpx 20rpx rgba(123, 154, 211, 0.808);
    background: cornflowerblue;
    position: fixed;
    bottom: 130rpx;
    right: 0;
    line-height: 80rpx;
    text-align: center;
    color: #fff;
  }

  .poster {
    margin: 0 auto;
    transition: all .3s ease-in;
  }

  .hidden {
    transform: translateY(200%);
  }
  .contarin{
    padding: 10rpx 32rpx;
    box-sizing: border-box;
    background: #fff;
  }
	
	.cite{
		overflow: hidden;
		 -webkit-line-clamp: 2;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
	}
	.cu-list.menu>.cu-item .content>view:first-child {
		display: -webkit-box;
		-webkit-box-align: left;
		-webkit-align-items: left;
		align-items: left;
	}
</style>
